package com.campus.counseling.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.counseling.entity.CounselorPrice;
import com.campus.counseling.model.mapper.CounselorPriceMapper;
import com.campus.counseling.service.CounselorPriceService;
import com.campus.counseling.model.common.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
public class CounselorPriceServiceImpl extends ServiceImpl<CounselorPriceMapper, CounselorPrice> implements CounselorPriceService {

    @Override
    @Transactional
    public void setPrice(CounselorPrice price) {
        // 检查是否已存在价格设置
        LambdaQueryWrapper<CounselorPrice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CounselorPrice::getCounselorId, price.getCounselorId());
        if (baseMapper.exists(wrapper)) {
            throw new ServiceException("已存在价格设置，请使用更新功能");
        }
        
        price.setCreateTime(LocalDateTime.now());
        price.setUpdateTime(LocalDateTime.now());
        price.setStatus("ENABLED");
        save(price);
    }

    @Override
    public CounselorPrice getPriceByCounselorId(Long counselorId) {
        LambdaQueryWrapper<CounselorPrice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CounselorPrice::getCounselorId, counselorId)
               .eq(CounselorPrice::getStatus, "ENABLED");
        return getOne(wrapper);
    }

    @Override
    @Transactional
    public void updatePrice(CounselorPrice price) {
        CounselorPrice existingPrice = getById(price.getId());
        if (existingPrice == null) {
            throw new ServiceException("价格设置不存在");
        }
        
        price.setUpdateTime(LocalDateTime.now());
        updateById(price);
    }

    @Override
    @Transactional
    public void updateStatus(Long id, String status) {
        CounselorPrice price = getById(id);
        if (price == null) {
            throw new ServiceException("价格设置不存在");
        }
        
        price.setStatus(status);
        price.setUpdateTime(LocalDateTime.now());
        updateById(price);
    }
} 